﻿using System.Diagnostics;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Navigation;
using System;
using System.Configuration;
using System.Linq;
using CustomerAssistant.Core;
using System.Web;

namespace CustomerAssistant
{
    /// <summary>
    /// OrderTip.xaml 的交互逻辑
    /// </summary>
    public partial class OrderTip : UserControl
    {
        static readonly string TIME_FMT = "yyMMddhh";
        public static readonly string UID = "open_id";
        public static readonly string TOKEN = "open_token";

        public OrderTip()
        {
            InitializeComponent();
            var tbNewCount = listbox1.FindName("tbNewCount");
            var tbOldCount = listbox1.FindName("tbOldCount");
        }

        private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            var link = ((Hyperlink)sender);
            string navigateUri = link.NavigateUri.ToString();
            Process.Start(new ProcessStartInfo(string.Compare(link.CommandParameter.ToString(), "new", true) == 0 ?
                CreateNewPlatformToken(Login.OperatorLoginData.OperatorID.ToString(), navigateUri).ToString() :
                CreateOldPlatformToken(Login.OperatorLoginData.OperatorName.ToString(), Login.OperatorLoginData.ClientID.ToString(), navigateUri).ToString()
                ));
            e.Handled = true;
        }

        static Uri CreateNewPlatformToken(string operatorId, string pathandquery)
        {
            var baseUrl = Properties.Settings.Default.newbaseUrl;
            var hash = Util.CreateMd5(DateTime.Now.AddHours(1).ToString(TIME_FMT) + operatorId);
            var param = string.Format("{0}={1}&{2}={3}", UID, operatorId, TOKEN, hash);
            return new Uri(string.Format("{0}{1}{2}{3}", baseUrl, pathandquery, (pathandquery.Contains('?') ? '&' : '?'), param));
        }

        static Uri CreateOldPlatformToken(string operatorName, string clientId, string pathandquery)
        {
            var baseUrl = Properties.Settings.Default.oldbaseUrl;
            var token = Util.CreateMd5(string.Format("{0}{1}3752", operatorName, DateTime.Now.AddHours(1).ToString("yyMMddhh")));
            return new Uri(string.Format("{0}/websiteembedding/logincheckbytoken.aspx?user={1}&cid={2}&tourl={3}&pwd={4}&cate=N1"
                , baseUrl, operatorName, clientId, HttpUtility.UrlEncode(pathandquery), token));
        }
    }
}